﻿namespace VertivWorkflowCommonService
{
    /// <summary>
    /// 
    /// </summary>
    public static class Util
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="LogLevel"></param>
        /// <param name="str"></param>
        public static void LogError(string LogLevel, string str)
        {
            Log(LogLevel, str);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="LogLevel"></param>
        /// <param name="str"></param>
        public static void LogVerbose(string LogLevel, string str)
        {
            if (LogLevel.ToUpper() != "VERBOSE")
                return;

            Log(LogLevel, str);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="logType"></param>
        /// <param name="content"></param>
        private static void Log(string logType, string content)
        {
            try
            {
                string logpath = System.AppDomain.CurrentDomain.BaseDirectory + "log\\" + DateTime.Now.GetDateTimeFormats('y')[0].ToString();
                if (!System.IO.File.Exists(logpath))
                {
                    DirectoryInfo di = Directory.CreateDirectory(logpath);
                }
                string logfilepath = logpath + "\\" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
                if (!System.IO.File.Exists(logfilepath))
                {
                    StreamWriter swq = File.CreateText(logfilepath);
                    swq.Close();
                }
                FileStream filewriter = new FileStream(logfilepath, FileMode.Append, FileAccess.Write);
                StreamWriter sw = new StreamWriter(filewriter);
                sw.WriteLine(logType + " at " + DateTime.Now.ToString());
                sw.WriteLine(content);
                sw.WriteLine();
                sw.Close();
                filewriter.Close();
            }
            catch
            {

            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <param name="other"></param>
        /// <returns></returns>
        public static T Merge<T>(this T obj, T other) where T : new() {
            var props = obj!.GetType().GetProperties();
            foreach (var prop in props) {
                var otherProp = other!.GetType().GetProperty(prop.Name);
                if (otherProp!.GetValue(other) != null) {
                    prop.SetValue(obj, otherProp.GetValue(other));
                }
            }
            return obj;
        } 
    }
}
